﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SignetKA.utils
{
    internal class SignetTool
    {
        internal static Bitmap ReadSignet(string path, string pwd)
        {
            var b_key = new byte[16];
            var b_iv = new byte[16];
            var b_keytag = new byte[16];
            using (var file = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                file.Position = 0;
                file.Read(b_key, 0, 16);
                file.Position = file.Length - 16;
                file.Read(b_keytag, 0, 16);
                if (EncryptTool.VerityPwd(pwd, b_key, b_keytag))
                {
                    file.Position = file.Length - 32;
                    file.Read(b_iv, 0, 16);

                    var buf = new byte[file.Position - 32-16];
                    file.Position = 16;
                    file.Read(buf, 0, buf.Length);
                    var bag = EncryptTool.MakeKeyIV(pwd, b_key, b_iv);
                    var img = EncryptTool.SM4Encryption.Decrypt(buf, bag.key_tag, bag.iv_tag);
                    var image = new Bitmap(new MemoryStream(img));
                    return image;
                }
            }
            return null;
        }
    }
}
